<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 提示消息 -->
      <el-alert
        title="添加商品信息"
        type="info"
        :closable="false"
        show-icon
        center>
      </el-alert>

      <!-- 添加商品步骤条 -->
      <el-steps :active="activeIndex - 0" finish-status="success" :space="200" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 添加商品tab栏 -->
      <el-form :model="addForm" :rules="addFormRules"
      ref="addFormRef" label-width="80px" label-position="top">
        <el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <!-- 商品基本信息tab栏 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="{
                  expandTrigger: 'hover',
                  value: 'cat_id',
                  label: 'cat_name',
                  children: 'children'
                }"
                clearable
                @change="cateChange"
                ></el-cascader>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品动态参数tab栏 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in this.manyParmList" :key="item.attr_id">
              <!-- 商品动态参数多选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                border
                v-for="(cb, i) in item.attr_vals"
                :label="cb"
                :key="i">
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品静态属性编辑栏 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
            v-for="(item, i) in this.onlyParmList"
            :key="i"
            :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品图片上传 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="this.uploadURL"
              :headers="headersObj"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>

          <!-- 商品内容编辑区域 -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addGoods" class="btnAdd">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 商品图片预览对话框 -->
      <el-dialog
        title="图片预览"
        :visible.sync="previewDialogVisible"
        width="50%">
        <el-image :src="previewPath"></el-image>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'

export default {
  data () {
    return {
      // 添加商品步骤条的默认选项为第一步
      activeIndex: 0,
      // 添加商品的表单数据对象
      addForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 商品分类列表
      cateList: [],
      // 选择的商品分类
      selectedKeys: [],
      // 动态参数列表
      manyParmList: [],
      // 静态属性列表
      onlyParmList: [],
      // 上传商品图片的URL
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传商品图片的token请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 商品图片的预览地址
      previewPath: '',
      previewDialogVisible: false,
      // 添加商品的表单数据校验规则
      addFormRules: {
        goods_name: { required: true, message: '请输入商品名称', trigger: 'blur' },
        goods_price: { required: true, message: '请输入商品价格', trigger: 'blur' },
        goods_weight: { required: true, message: '请输入商品重量', trigger: 'blur' },
        goods_number: { required: true, message: '请输入商品数量', trigger: 'blur' },
        goods_cat: { required: true, message: '请选择商品分类', trigger: 'change' }
      }
    }
  },
  created () {
    this.getCateList()
  },
  computed: {
    // 获取当前选中的分类id
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return []
    }
  },
  methods: {
    // 获取所有商品分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('/categories', { params: { type: 3 } })
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败！')
      this.cateList = res.data
    },
    // 获取添加商品的分类
    cateChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.$message.error('只能选择三级商品分类！')
        this.addForm.goods_cat = []
        return false
      }
    },
    // 控制tab栏的切换
    beforeTabLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类！')
        return false
      }
    },
    // 获取选中商品分类的参数与属性
    async getParm () {
      const { data: res } = await this.$http.get(`/categories/${this.addForm.goods_cat[2]}/attributes`, { params: { sel: this.parm } })
      if (res.meta.status !== 200) return this.$message.error('获取失败！')
      this.$message.success('获取成功！')
      res.data.forEach(item => {
        // 判断参数标签是否为空
        item.attr_vals = item.attr_vals ? item.attr_vals = item.attr_vals.split(' ') : []
      })
      if (this.activeTabName === 'many') {
        this.manyParmList = res.data
      } else {
        this.onlyParmList = res.data
      }
    },
    // 当前的tab栏
    async tabClicked () {
      // 当前为动态参数tab栏 请求动态参数列表
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`/categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        if (res.meta.status !== 200) return this.$message.error('获取失败！')
        this.$message.success('获取成功！')
        res.data.forEach(item => {
          // 判断参数标签是否为空
          item.attr_vals = item.attr_vals ? item.attr_vals = item.attr_vals.split(' ') : []
        })
        this.manyParmList = res.data
      }

      // 当前为静态属性tab栏 请求静态属性列表
      if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`/categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status !== 200) return this.$message.error('获取失败！')
        this.$message.success('获取成功！')
        this.onlyParmList = res.data
      }
    },
    // 处理商品图片预览效果
    handlePreview (file) {
      this.previewPath = file.response.data.url
      // 打开图片预览对话框
      this.previewDialogVisible = true
    },
    // 处理移除商品图片的操作
    handleRemove (file) {
      // 获取要移除图片的临时路径
      const filePath = file.response.data.tmp_path
      // 获得addForm中图片的索引值
      const i = this.addForm.pics.findIndex(item => item.pic === filePath)
      // 通过索引值移除图片
      this.addForm.pics.splice(i, 1)
    },
    // 监听图片上传成功的事件
    handleSuccess (response) {
      const picInfo = { pic: response.data.tmp_path }
      this.addForm.pics.push(picInfo)
    },
    // 添加商品
    addGoods () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请完善商品信息！')
        // 通过loadsh的cloneDeep进行深拷贝
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')

        // 处理动态参数
        this.manyParmList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyParmList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败！')
        this.$message.success('添加商品成功！')
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-checkbox {
  margin: 0 5px 0 0 !important;
}

.btnAdd {
  margin-top: 15px;
}
</style>
